package com.atguigu.bigdata.spark.core.rdd.persist;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

public class Spark04_RDD_Persist_JAVA {
    /*
        checkpoint 需要落盘，需要指定检查点保存路径
        检查点路径保存的文件，当作业执行完毕后，不会被删除
        一般保存路径都是在分布式存储系统：HDFS

        所谓的检查点其实就是通过将RDD中间结果写入磁盘
        由于血缘依赖过长会造成容错成本过高，这样就不如在中间阶段做检查点容错，如果 检查点
        之后有节点出现问题， 可以从检查点开始重做血缘 ，减少了开销。
     */
    public static void main(String[] args) {
        // 1.创建配置对象
        SparkConf conf = new SparkConf().setMaster("local[*]").setAppName("sparkCore");

        // 2. 创建sparkContext
        JavaSparkContext sc = new JavaSparkContext(conf);
        sc.setCheckpointDir("cp");
        JavaRDD<String> rdd = sc.parallelize(Arrays.asList("hello word", "hello spark", "hive","java"));

        JavaRDD<String> flatmap = rdd.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public Iterator<String> call(String s) throws Exception {
                String[] temp = s.split(" ");
                return Arrays.asList(temp).iterator();
            }
        });
        JavaPairRDD<String, Integer> pairMap = flatmap.mapToPair(new PairFunction<String, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(String s) throws Exception {
                System.out.println("@@@@@@@@@@@@@@@@");
                return new Tuple2<String, Integer>(s, 1);
            }
        });

        pairMap.checkpoint();

        JavaPairRDD<String, Integer> reduceByKey = pairMap.reduceByKey(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer integer, Integer integer2) throws Exception {
                return integer + integer2;
            }
        });

        System.out.println(reduceByKey.collect().toString());

        System.out.println("-----------------------------------");

        JavaPairRDD<String, Iterable<Integer>> groupbyKey = pairMap.groupByKey();

        System.out.println(groupbyKey.collect().toString());

        sc.stop();
    }
}
